
	var autoSaveDelay = 10;
	var fileDialogCurrentCategory = "";
	var waitingCategory = false;
	var autoSaving = false;
	var lastSave = "";
	var hasChanges = false;

	var CMS_ALLOWCOMMENTS = 2;
	var CMS_ALLOWRATING = 4;
	var CMS_SEXYBAR = 8;
	
	if (!Array.prototype.forEach){
	  Array.prototype.forEach = function(fun){
		var len = this.length >>> 0;
		if (typeof fun != "function") throw new TypeError();
	
		var thisp = arguments[1];
		for (var i = 0; i < len; i++){
		  if (i in this)
			fun.call(thisp, this[i], i, this);
		}
	  };
	}
	
	$.ctrl = function(key, callback, args) {
			$(document).keydown(function(e) {
				if(!args) args=[];
				if(e.keyCode == key.charCodeAt(0) && (e.ctrlKey || e.metaKey)) {
					callback.apply(this, args);
					return false;
				}
			});
		};
	
	function insertHtmlAtCursor(html) {
		var range, node;
		if (window.getSelection && window.getSelection().getRangeAt) {
			range = window.getSelection().getRangeAt(0);
			node = range.createContextualFragment(html);
			range.insertNode(node);
		} else if (document.selection && document.selection.createRange) {
			document.selection.createRange().pasteHTML(html);
		}
	}
	
	function chooseCategory(){
		
		waitingCategory = false;
		$('#fileDialog').dialog('close');
		$('#btnChooseCategory').hide();
		save();
		
	}
	
	function changeCategory(){
		fileDialogCurrentCategory = "";
		save();
	}
	
	function insertAttachmentLink(id, name){
		
		if(!$('#statusbar a.preview').hasClass('selected')){
			alert(strings.pleaseChangeToPreview);
			return;
		}
		
		insertHtmlAtCursor(
		  $('<span>')
		  .append($('<a>').attr('href', '/cms/download.php?id=' + id).text(name)).html()
		   );
	}
	
	function embedAttachment(path, name){
		
		if(!$('#statusbar a.preview').hasClass('selected')){
			alert(strings.pleaseChangeToPreview);
			return;
		}
		
		insertHtmlAtCursor(
		  $('<span>')
		  .append($('<img>').attr({src: '/cms-data/files/' + path, alt: name})).html()
		   );
	}

	function loadAttachmentsTab(){
		if(!$('#id').val()){
			$('#attachments').text(strings.mustSaveDocument);
		}else{	
			$('#attachments')
			.html('')
			.append(
			   $('<iframe>')
				.attr('src', 'attchs.php?idcontent=' + $('#id').val())
				.css({ width: '100%', height: '100%', border: 'none', background: "white" })
			   );
		}
		
	}
	
	function loadCommentsTab(){
		if(!$('#id').val()){
			$('#comments-tab').text(strings.mustSaveDocument);
		}else{	
			$('#comments-tab').css({'overflow': 'auto', 'background-color': 'white'});
			loadComments();
		}
	}
	
	function ban(iconElement){
		
		var id = $(iconElement).parent().find('.idcomment').text();
		var deleted = $(iconElement).parent().find('.deleted').text();
		
		if(deleted > 0){
			$(iconElement).parent().parent().removeClass('comment-banned');
			$(iconElement).parent().find('.deleted').text(0);
			status(strings.unbanning, true);
			$.post('editor-comments.php', { unban: id }, 
				function(data){
					if(data != 'OK'){
						alert(strings.error + data);
					}
					status();
				})
		}else{
			$(iconElement).parent().parent().addClass('comment-banned');
			$(iconElement).parent().find('.deleted').text(1);
			$.post('editor-comments.php', { ban: id }, 
				function(data){
					status(strings.banning, true);
					if(data != 'OK'){
						alert(strings.error + data);
					}
					status();
				})
		}
		
	}
	
	function loadComments(){
		$('#comments-tab').html('');
		status(strings.loadingComments, true);
		$.getJSON('editor-comments.php', { idcontent: $('#id').val() }, 
			function(data){  
				status();
				data.forEach(
					function(comment){
						$('#comments-tab')
							.append(
								$('<div>')
									.addClass('comment ' + (comment.deleted > 0 ? 'comment-banned' : ''))
									.append( $('<div>')
											   .text(comment.name ? comment.name : strings.anonymous).css('font-style', 'italic')
											   .append( $('<div>').addClass('invisible idcomment').text(comment.idcomment) )
											   .append( $('<div>').addClass('invisible deleted').text(comment.deleted) )
											   .append(  $('<div>').addClass('icon icon-ban').attr('title', strings.banUnban).css({ 'float': 'right', 'display': 'none' }).click(function(){ ban(this); }) )
											   
											   )
									.append( $('<a>').attr('href', 'mailto:' + comment.mail).text(comment.mail) )
									.append( $('<div>').text(comment.title).css('font-weight', 'bold') )
									.append( $('<div>').text(comment.text) )
									.mouseenter(function(){ 
										$(this)
											.css({'background': '#ddd', 'max-height': 'none'})
											.find('.icon-ban').show() 
									})
									.mouseleave(function(){ 
										$(this)
											.css({'background': 'none', 'max-height': '100px'})
											.find('.icon-ban').hide()
									})
							);
					});			
			});
	}
	
	function loadHistoryTab(){
		if(!$('#id').val()){         
			$('#history').text(strings.mustSaveDocument);
		}else{	
			$('#history')
				.html('')
				.append(
						$('<div>')
							.addClass('toolbar')
							.append( $('<button>')
							.click(function(){ loadHistory(); })
							   .append($('<div>')
								 .addClass('icon icon-refresh')
								 .attr('title', strings.reloadHistory)
								  ))
							.append( $('<div>').addClass('separator') )
							.append( $('<button>')
							.click(function(){ addHistoryEntry(); })
							   .append($('<div>')
								 .addClass('icon icon-newhistory')
								 .attr('title', strings.addHistoryEntry)
								 ))
						)
				.append(
				   $('<div>')
				   		.css({padding: '1em', height: '90%', background: 'white', 'overflow': 'auto'})
						.append(
						   $('<div>')
							.attr('id', 'history-list')
							.css({ width: '100%', height: '90%', border: 'none', background: 'white' })
						   ));
				loadHistory();
		}
	}
	
	function addHistoryEntry(){
		
		var comment = prompt(strings.enterCommentForHistory, '');
		
		if(comment){
			$.get('log.get.php', {comment: comment, idcontent: $('#id').val() }, function(data){ loadHistory(); });
		}
		
	}
	
	function loadHistory(){
		
		$('#history-list').html('');
		
		status(strings.loadingHistory, true);
		
		$.getJSON('log.get.php', { idcontent: $('#id').val() }, 
			function(data){
				data.forEach(function(entry){
					$('#history-list').append(modelHistoryEntry(entry));
				});
				status();
			});
	}
	
	function actionFor(action){
		switch(action){
			case "1":
				return strings.createdContent;
			case "2":
				return strings.modifiedContent;
			case "3":
				return strings.attachedFile;
			case "4":
				return strings.dettachedFile;
			case "5":
				return strings.commented;
			case "6":
				return strings.opened;
		}
	}
	
	function modelHistoryEntry(entry){
		return  $('<div>')
				.addClass('history-entry')
				.append( $('<div>').addClass('date').text(entry.date) )
				.append( $('<span>').addClass('user').text(entry.cmsUser_iduser) )
				.append( $('<span>').addClass('action').text(actionFor(entry.action)) )
				.append( $('<span>').addClass('data').text(entry.text) )
				;
				
	}

	function checkChanges(){
		
		if(lastSave != $('#editor').html()){
			hasChanges = true;
		}else{
			hasChanges = false;
		}
		
	}

	function isInt(value){
		numbers = "1234567890";
		for(i = 0; i < value.length; i++){
			if(numbers.indexOf(value.charAt(i)) < 0)
				return false;
		}
		return true;
	}
	
	function autoSave(){
		
		checkChanges();
		
		if(hasChanges){ 
		
			autoSaving = true;
			
			save();
			
		}
		
		setTimeout('autoSave()', autoSaveDelay * 1000);
		
	}
	
	function cleanFormat(){
		
		if($('#statusbar a.preview').hasClass('selected')){
			
			$('#editor * ')
				.removeAttr('style')
				.removeAttr('class');
			
		}else{
			
			var tmp = $('<div>').html($('#editor').text());
			
			tmp.find('*')
				.removeAttr('style')
				.removeAttr('class');
				
			$('#editor').text(tmp.html());
			
		}
		
	}
	
	function save(){
		
		
		id = $('#id').val();
		categ = fileDialogCurrentCategory;
		title = $('#title').val();
		intro = $('#intro').val();
		text = $('#statusbar a.preview').hasClass('selected') ? $('#editor').html() : $('#editor').text() ;
		online = $('#online:checked').size() ? 1 : 0;
		comments = $('#comments:checked').size() ? CMS_ALLOWCOMMENTS : 0;
		rating = $('#rating:checked').size() ? CMS_ALLOWRATING : 0;
		sexybar = $('#sexybar:checked').size() ? CMS_SEXYBAR : 0;
		editlevel = $('#editlevel').val();
		readlevel = $('#readlevel').val();
		
		if(!title){
			if(autoSaving){
				title = strings.autoSavedBracket + text;
				autosaving = 0;
			}else{
				alert(strings.titleMissing);
				return;
			}
		}
		
		
		if(!categ){
			if(autoSaving){
				categ = "NULL";
			}else{
				waitingCategory = true;
				showFileDialog();
				return;
			}
		}
		
		if(!intro && !autoSaving){
			if(!confirm(strings.introMissingConfirm))
				return;
		}
		
		if(autoSaving){
			status(strings.autoSaving, true);
		}else{
			status(strings.saving, true);
		}
		
		lastSave = $('#editor').html();
		
		$.ajax({
			url:'editor-save.php',
			type: 'POST',
			data: { 
				idcontent: id, 
				cmsCategory_idcategory: categ,
				title: title, 
				intro: intro, 
				text: text,
				created: created,
				modified: modified,
				online: online,
				options: comments | sexybar | rating ,
				editlevel: editlevel,
				readlevel: readlevel
				},
			success: function(data){
				
				if(isInt(data)){
					$('#id').val(data);
					status(strings.savedOk);
				}else{
					alert(strings.saveError + "\n" + data);
					status(strings.savedError);
				}
				
				if(autoSaving){
					autoSaving = false;
					status(strings.autoSaved);
				}
				
			}
			   });
	}//End save()

	function status(message, loader){
		
		var s = $('#statusbar div');
		
		if(!message){
			status(strings.ready);
			return;
		}
		
		s.html('');
		
		if(loader){
			s.append($('<img>').attr({'src': 'css/loader.gif', 'align': 'absmiddle', 'hspace': 3}));
		}
		
		s.append(message);
		
	}
	
	function showFileDialog(){
		
		
		if(waitingCategory){
			$('#fileDialog').attr('title', strings.chooseCategory);
			$('#btnChooseCategory').show();
		}else{
			
			checkChanges();
		
			if(hasChanges){
				if(confirm(strings.wantSaveChangesQuestion)){
					save();
				}
			}
			
			$('#fileDialog').attr('title', strings.openContent);
			$('#btnChooseCategory').hide();
		}
		
		$('#fileDialog').dialog({ 
			modal:true,
			width: 500,
			height:500,
			open: function(){ refreshFileDialog(); }
		});
	}
	
	function refreshFileDialog(){
		
		status(strings.loadingFiles, true);
		
		$('#fileDialog table')
			.html('')
			.append(
				$('<tr>')
					.append($('<th>').attr('width', '5%'))
					.append($('<th>').append('Title').attr('width', '60%'))
					.append($('<th>').append('Modified'))
					
				  );
		
		$.getJSON('editor-open.php', {  idcategory: fileDialogCurrentCategory },
			  function(data){
				status(strings.filesLoaded);
				data.forEach(function(c){
						if(c.idcontent){
							$('#fileDialog table')
								.append(
									$('<tr>')
										.append( $('<td>').append($('<div>').addClass('icon icon-content') ) )
										.append($('<td>').append($('<div>').append(c.title)))
										.append($('<td>').append(c.modified))
										.append($('<input>').attr({type: 'hidden', value: c.idcontent}))
										.mouseenter(function(){
											$(this).css({ 'background-color': '#eee' });					 
										})
										.mouseleave(function(){
											$(this).css({ 'background-color': 'white' });
										})
										.click(function(){
											openContent($(this).children('input').val());
										})
									  );
						}else if(c.idcategory){
							$('#fileDialog table')
								.append(
									$('<tr>')
										.append( $('<td>').append($('<div>').addClass('icon icon-folder') ) )
										.append($('<td>').append($('<div>').append(c.name)))
										.append($('<td>'))
										.append($('<input>').attr({type: 'hidden', value: c.idcategory}))
										.mouseenter(function(){
											$(this).css({ 'background-color': '#eee' });					 
										})
										.mouseleave(function(){
											$(this).css({ 'background-color': 'white' });
										})
										.click(function(){
											fileDialogCurrentCategory = $(this).children('input').val();
											refreshFileDialog();
											/*if(waitingCategory){
												waitingCategory = false;
												$('#fileDialog').dialog('close');
												save();
											}else{
												refreshFileDialog(); //To access new category folder
											}*/
											
											
										})
									  );
						}//end if(c.idcontent)
					}) //end forEach 
			  });//end getjson
	}
	
	function openContent(id){
		
		status("Opening content...", true);
		
		$.getJSON('editor-open.php', { idcontent: id },
				  function(data){
					  
					  if(data.title.substring(0, strings.autoSavedBracket.length - 0) == strings.autoSavedBracket){
						  data.title = "";
					  }
					  
					  if(!data){
						  alert(strings.errorOpeningContent);
					  }else{
						  $('#title').val(data.title);
						  $('#intro').val(data.intro);
						  $('#created').val(data.created);
						  $('#modified').val(data.modified);
						  $('#online').attr('checked', (data.online == "1" ? true : false));
						  $('#comments').attr('checked', ( (data.options & CMS_ALLOWCOMMENTS) == CMS_ALLOWCOMMENTS ? true : false));
						  $('#rating').attr('checked', ( (data.options & CMS_ALLOWRATING) == CMS_ALLOWRATING ? true : false));
						  $('#sexybar').attr('checked', ( (data.options & CMS_SEXYBAR) == CMS_SEXYBAR ? true : false));
						  $('#category').val(fileDialogCurrentCategory);
						  $('#editor').html(data.text);
						  $('#id').val(data.idcontent);
						  $('#editlevel').val(data.editlevel);
						  $('#readlevel').val(data.readlevel);
						  fileDialogCurrentCategory = data.cmsCategory_idcategory;
					  		
					  }
					  
					  lastSave = $('#editor').html();
					  
					  status(strings.ready, false);
					  
					  $('#tabs li:nth-child(1)').click();
					  
					  $('#fileDialog').dialog('close');
				  });
		
	}
	
	function goTab(tab){
		
		$('#tabs li.selected').removeClass('selected');
		
		$('#tabs li:nth-child(' + tab + ')').addClass('selected');
		
		$('#properties, #attachments, #history, #comments-tab').hide();
		
		switch(tab){
			case 1:
				$('#properties').show(); 
				break;
			case 2:
				$('#attachments').show(); 
				loadAttachmentsTab();
				break;
			case 3:
				$('#comments-tab').show(); 
				loadCommentsTab();
				break;
			case 4:
				$('#history').show(); 
				loadHistoryTab();
				break;
		}
		
	}
	
	function newCategory(){
		var catname = prompt(strings.newCategoryName, "");
					
		if(!catname) return;
		
		status(strings.savingCategory, true);
		
		$.getJSON('editor-newcat.php', { name: catname, idcategory: fileDialogCurrentCategory }, 
		   function(data){
			   status(strings.categorySaved);
			   refreshFileDialog();
		   });
	}
	
	function changeView(aElement){
		
		var a = $(aElement);
		
		if(a.hasClass('preview')){
			if(!a.hasClass('selected')){
				$('#editor').html($('#editor').text());
			}
		}else{
			if(!a.hasClass('selected')){
				$('#editor').text($('#editor').html());
			}
		}
		
		$('#statusbar a').removeClass('selected');
		
		a.addClass('selected');
	}
	
	function load_recent(){
		status(strings.wait, true);
		
		$('#menu-right').html('');
		
		$.getJSON('editor-open.php', { recent: 1 },
		function(data){
			
			status();
			
			if(!data) return;
			
			data.forEach(function(c){
							$('#menu-right')
								.append( $('<li>')
										   .append( $('<div>').addClass('invisible idcontent').text(c.idcontent) )
										   .append(c.title)
										   .click(function(){
												openContent($(this).find('.idcontent').text());
												hideMenu();
											}) );
						});
		});
	}
	
	function start_click(){
		$('#menu').toggle();
		
		if($('#menu').is(':visible')){
			load_recent();
		}
	}
	
	function editor_click(){
		if( $('#menu').is(':visible') ){
			$('#menu').hide();
		}
	}
	
	function saveAs(){
		$('#id').val('');
		changeCategory();
	}
	
	function logOut(){
		document.location = 'logout.php';
	}
	
	function hideMenu(){
		$('#menu').hide();
	}

	$(function(){
		$('#top .toolbar .icon, #tabs div, #tabs li').parent().mousedown(function(evt){ evt.preventDefault(); });
		
		$('.icon-new, .icon-new-32').parent()
			.click(function(){
				document.location = 'editor.php';
			});
		
		$('.icon-open, .icon-open-32').parent()
			.attr('title', strings.openContent)
			.click(function(){
				showFileDialog();
			});
		
		$('.icon-newfolder').parent()
			.attr('title', strings.createNewCategory)
			.click(function(){ newCategory() });
		
		$('.icon-back').parent()
			.attr('title', strings.backToAllCategories)
			.click(function(){
				fileDialogCurrentCategory = "";
				refreshFileDialog();
			});
		
		$('.icon-save, .icon-save-32').parent()
			.attr('title', strings.save)
			.click(function(){	
				save();
				});
		$('.icon-bold').parent()
			.attr('title', strings.bold)
			.click(function(evt){
				document.execCommand('bold', false, null);
			});
			
		$('.icon-italic').parent()
			.attr('title', strings.italic)
			.click(function(){
				document.execCommand('Italic', false, null);
			});
		$('.icon-underline').parent()
			.attr('title', strings.underline)
			.click(function(){
				document.execCommand('Underline', false, null);
			});
		$('.icon-clean').parent()
			.attr('title', strings.cleanFormat)
			.click(function(){
				cleanFormat();
			});
		$('.icon-indent').parent()
			.attr('title', strings.indent)
			.click(function(){
				document.execCommand('Indent', false, null);
			});
		$('.icon-outdent').parent()
			.attr('title', strings.outdent)
			.click(function(){
				document.execCommand('Outdent', false, null);
			});
		$('.icon-ol').parent()
			.attr('title', strings.insertOl)
			.click(function(){
				document.execCommand('InsertOrderedList', false, null);
			});
		$('.icon-ul').parent()
			.attr('title', strings.insertUL)
			.click(function(){
				document.execCommand('InsertUnorderedList', false, null);
			});
		$('.icon-left').parent()
			.attr('title', strings.justifyLeft)
			.click(function(){
				document.execCommand('justifyLeft', false, null);
			});
		$('.icon-center').parent()
			.attr('title', strings.justifyCenter)
			.click(function(){
				document.execCommand('justifyCenter', false, null);
			});
		$('.icon-right').parent()
			.attr('title', strings.justifyRight)
			.click(function(){
				document.execCommand('justifyRight', false, null);
			});
		$('.icon-justify').parent()
			.attr('title', strings.justifyText)
			.click(function(){
				document.execCommand('justifyJustified', false, null);
			});
		$('.icon-undo').parent()
			.attr('title', strings.undo)
			.click(function(){
				document.execCommand('Undo', false, null);
			});
		$('.icon-redo').parent()
			.attr('title', strings.redo)
			.click(function(){
				document.execCommand('Redo', false, null);
			});
			
		$('.icon-link').parent()
			.attr('title', strings.insertLink)
			.click(function(){
				document.execCommand('createLink', false, prompt(strings.enterUrl, 'http://'));
			});
			
		$('.icon-user').parent()
			.attr('title', strings.manageUsers)
			.click(function(){
				window.open('usereditor.php', 'userMgmt');
			});
			
		$('#btnChangeCategory')
			.text(strings.changeCategory)
			.click(function(){ changeCategory() });
		
		$('#btnChooseCategory')
			.text(strings.chooseCategory)
			.click(function(){ chooseCategory() });
			
		$('#statusbar a').click(function(){ changeView(this); });
		
		$('form').submit(function(){ return false; });
		
		
		$('#formatting')
			.append($('<option>').append(strings.formatting))
			.append($('<option>').append(strings.h1).attr('value', 'h1'))
			.append($('<option>').append(strings.h2).attr('value', 'h2'))
			.append($('<option>').append(strings.h3).attr('value', 'h3'))
			.append($('<option>').append(strings.normal).attr('value', 'div'))
			.append($('<option>').append(strings.blockquote).attr('value', 'bloquote'))
			.append($('<option>').append(strings.monospace).attr('value', 'pre'))
			.change(function(){
				if($(this).val())
					document.execCommand('FormatBlock', false, $(this).val());
			})
			
		$('#title')
			.change(function(){ document.title = $(this).val(); });


		$('#tabs li:nth-child(1)').click(function(){ goTab(1); }).click();
		$('#tabs li:nth-child(2)').click(function(){ goTab(2); });
		$('#tabs li:nth-child(3)').click(function(){ goTab(3); });
		$('#tabs li:nth-child(4)').click(function(){ goTab(4); });
		
		lastSave = $('#editor').html();
		
		//setTimeout('autoSave()', autoSaveDelay * 1000);
		
		$('button.start')
			.text(strings.productName)
			.click(function(){ start_click(); });
			
		$('#menu li')
			.click(function(){ hideMenu(); });
		
		$('.icon-new-32')
			.parent()
			.find('label').text(strings.newWord);
		
		$('.icon-open-32')
			.parent()
			.find('label').text(strings.open);
			
		$('.icon-save-32')
			.parent()
			.find('label').text(strings.save);
			
		$('.icon-saveas-32')
			.parent()
			.find('label').text(strings.saveAs)
			.click(function(){ saveAs(); });
		
		$('.icon-savename-32')
			.parent()
			.find('label').text(strings.changeCategory)
			.click(function(){ changeCategory(); });
			
		$('#menu .logout')
			.text(strings.logout)
			.click(function(){ logOut(); });
			
		$('#editor')
			.click(function(){ editor_click(); });
			
		$('#tabs li:nth-child(1)').attr('title', strings.properties);
		$('#tabs li:nth-child(2)').attr('title', strings.attachments);
		$('#tabs li:nth-child(3)').attr('title', strings.comments);
		$('#tabs li:nth-child(4)').attr('title', strings.history);
		$('#lblTitle').text(strings.contentTitle);
		$('#lblIntro').text(strings.contentIntro);
		$('#lblCreated').text(strings.creationDate);
		$('#lblModified').text(strings.modificationDate);
		$('#lblOnline').text(strings.online);
		$('#lblAllowComments').text(strings.allowComments);
		$('#lblAllowRating').text(strings.allowRating);
		$('#lblSecurity').text(strings.security);
		$('#lblSexy').text(strings.sexyBar);
		$('#lblLevel').text(strings.myLevelIs + myLevel);
		$('#lblReadLevel').text(strings.readLevel);
		$('#lblEditLevel').text(strings.editLevel);
		$('#lblContent').text(strings.content);
		$('#lblDates').text(strings.dates);
		$('.preview').text(strings.preview);
		
		
		$.ctrl('S', function(){ save(); });
		$.ctrl('O', function(){ showFileDialog(); });
		$.ctrl('N', function(){ $('.icon-new').parent().click(); });
		
		$(window).bind('beforeunload', 
			function() {
				checkChanges();
				if (hasChanges) {
					return strings.warningUnsavedChanges;
				}
			});
		
		status();
		
	});

